package rcs34.android.AndroidRC;

import java.io.File;
import java.util.Arrays;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Environment;

public class FileManager {
  public final static String ROOT = Environment.getExternalStorageDirectory()
      .getAbsolutePath();
  
  synchronized public static JSONObject lsAsJSON(File _file) {
    //System.out.println(_file.getAbsolutePath());
    if (_file.exists()) {
      try {
        JSONObject ls = new JSONObject();
        ls.put(CommDefs.KEY_FILE, new FileInfo(_file, ROOT));
        if (_file.isDirectory()) {
          File[] fItems = _file.listFiles();
          JSONObject items = new JSONObject();
          for (int i = 0; i < fItems.length; i++) {
            FileInfo fileInfo = new FileInfo(fItems[i], ROOT);
            items.put(fileInfo.path, fileInfo);
          }
          ls.put(CommDefs.KEY_LS, items);
        }
        return ls;
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return null;  
  }
  
  public static JSONObject delete(String _jsonFiles) {
    JSONObject report = new JSONObject();
    try {
      JSONArray files = new JSONArray(_jsonFiles);
      int errors = 0;
      int deleted = 0;
      String errMessage = "";
      for (int i = 0; i < files.length(); i++) {
        File toDelete = new File(ROOT+files.getString(i));
        if (toDelete.exists()) {
          if (!toDelete.isDirectory() || toDelete.list().length == 0) {
            if (toDelete.delete()) {
              deleted++;
            } else {
              errors++;
              errMessage += "Deleteing of '" + toDelete + "' failed;";
            }
          } else {
            errors++;
            errMessage += "Directory '" + toDelete + "' is not empty;";
          }
        } else {
          errors++;
          errMessage += toDelete + " does not exist;";
        }
      }
      report.put("deleted", deleted);
      report.put("errors", errors);
      report.put("message", errMessage);
    } catch (JSONException _e) {
      _e.printStackTrace();
    }
    return report;
  }
}
